/*--------------------玩家键盘移动控制----------------------------*/
const playerDirection = new THREE.Vector3(); // 玩家方向
export default function pcControls( deltaTime ,playerCamera) {
    const speedDelta = deltaTime * ( playerOnFloor ? 25 : 8 );
    if ( keyStates[ 'KeyW' ] ) {
        playerVelocity.add( getForwardVector().multiplyScalar( speedDelta ) );
        rotation(playerCamera)
    }
    if ( keyStates[ 'KeyS' ] ) {
        playerVelocity.add( getForwardVector().multiplyScalar( - speedDelta ) );
        rotation(playerCamera)
    }
    if ( keyStates[ 'KeyA' ] ) {
        playerVelocity.add( getSideVector().multiplyScalar( - speedDelta ) );
        rotation(playerCamera)
    }
    if ( keyStates[ 'KeyD' ] ) {
        playerVelocity.add( getSideVector().multiplyScalar( speedDelta ) );
        rotation(playerCamera)
    }
    if ( playerOnFloor ) {
        if ( keyStates[ 'Space' ] ) {
            playerVelocity.y = 15;
        }
    }
}

// 事件绑定
document.addEventListener( 'keydown', ( event ) => {
    keyStates[event.code] = true;
} );
let timer
document.addEventListener( 'keyup', ( event ) => {
    action.run.stop()
    action.walking.play(); 
    clearTimeout(timer)
    timer = setTimeout(() => {
        walking=false
        action.walking.stop()
        action.idle.play(); 
    },800)
   
    keyStates[ event.code ] = false;
} );
// 获取玩家当前朝向坐标
function getForwardVector() {
    camera.getWorldDirection( playerDirection );
    playerDirection.y = 0;
    playerDirection.normalize();
    return playerDirection;
}
// 获取玩家侧面坐标
function getSideVector() {
    camera.getWorldDirection( playerDirection );
    playerDirection.y = 0;
    playerDirection.normalize();
    playerDirection.cross( camera.up );
    return playerDirection;
}
// 人物旋转
function rotation(playerCamera){
    let actor = scene.getObjectByName("actor");
    let direct=getDirectPoint()
    playerCamera.lookAt(direct.x, player.position.y, direct.z);
    let point= playerCamera.quaternion.clone();
  
    actor.quaternion.slerp(point, 0.1);
    action.idle.stop();
    action.run.play()
    walking=true
}

// 获取玩家指向的点
function getDirectPoint(){
    let point1=playerDirection.clone() // 当前相机朝向
    let point2=player.position.clone() // 玩家位置
    // 向量在玩家身上指向外界空间
    point1.add(point2) // 顺相机方向 玩家指向的单位点
    return point1
}